<?php namespace App\Controllers;

use \App\App;

class Shelf extends App
{
    public function __construct()
    {
        parent::__construct();
        if (!$this->user) {
            $this->request->isAjax()?
            $this->showJson("您还未登录，请登录后重试。","error"):
            showError("您还未登录，请登录后重试。",'',"用户未登录",['url'=>site_url('/user'),'page'=>'登录']);
        }
    }

    public function index()
    {
        $page=$this->request->get("page");
        $favoritesModel=new \App\Models\Favorites();

        $story=$favoritesModel->findByUser($this->user['id'],0,true);
        $this->view->stories=$story;
        $this->view->viewTitle="我的书架";
        $this->render("/front/user/shelf","/front/header");
    }

    public function favorites($storyid) {
        if (!$storyid || $storyid=="undefined") {
            $this->showJson("您未选择要收藏的小说。","error");
        }

        $favoritesModel=new \App\Models\Favorites();
        $storyModel=new \App\Models\Story();
        $story=$storyModel->find($storyid);
        if ($check=$favoritesModel->check($this->user['id'],$storyid)) {
            $favoritesModel->delete($check['id']);
            $story['favorites']--;
            $message="您已经取消收藏此书";
        }else {
            $favorites=['user'=>$this->user['id'],'story'=>$storyid];
            $favoritesModel->save($favorites);
            $story['favorites']++;
            $message="您已经收藏此书";
        } 
        $storyModel->set("favorites",$story['favorites'])->update(null,['id'=>$story['id']]);

        if ($storyModel->error()) {
            $this->showJson($storyModel->error(),"error");
        }
        $this->showJson($message,"success");
    }
}